package tool

import (
	"bytes"

	"github.com/disintegration/imaging"

	"image"
	"image/color"
	"image/draw"
	"image/jpeg"
	_ "image/png"
	"io"
)

// PngToJpg 转化图片格式 并调整尺寸，设置背景颜色
func PngToJpg(r io.Reader, quality int, bg color.Color, w int, h int) (*bytes.Buffer, error) {
	img, _, err := image.Decode(r)
	if err != nil {
		return nil, err
	}

	// 创建一个与原图片尺寸相同的新图片，背景颜色为白色
	newImg := image.NewRGBA(img.Bounds())
	//fmt.Println("Size:", newImg.Bounds().Size().X, newImg.Bounds().Size().Y)
	draw.Draw(newImg, newImg.Bounds(), &image.Uniform{C: bg}, image.Point{}, draw.Src)
	// 将原始图片绘制到新图片上，这样透明区域就会被白色填充
	draw.Draw(newImg, img.Bounds(), img, image.Point{}, draw.Over)
	//调整尺寸
	resizeImg := imaging.Resize(newImg, w, h, imaging.Lanczos)

	buf := new(bytes.Buffer)
	options := jpeg.Options{Quality: quality}
	err = jpeg.Encode(buf, resizeImg, &options)
	if err != nil {
		return nil, err
	}

	return buf, nil
}

func ResizeImg(contents []byte, quality int, w int, h int) ([]byte, error) {
	img, _, err := image.Decode(bytes.NewReader(contents))
	if err != nil {
		return nil, err
	}
	resizedImg := imaging.Resize(img, w, h, imaging.Lanczos)
	var buf bytes.Buffer
	err = jpeg.Encode(&buf, resizedImg, &jpeg.Options{Quality: 80})
	if err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}
